import 'package:flutter_shop/cons/global_cons.dart';
import 'package:flutter_shop/jpush/jpush_service.dart';
import 'package:flutter_shop/pages/base/base_presenter.dart';
import 'package:flutter_shop/pages/common/login/entity/base_info.dart';
import 'package:flutter_shop/pages/common/login/entity/user_info.dart';
import 'package:flutter_shop/pages/common/login/login_contract.dart';
import 'package:flutter_shop/pages/common/login/login_model.dart';
import 'package:flutter_shop/routers/navigator_utils.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:fluwx/fluwx.dart';

/// Title:LoginPresenter <br/>
/// Description: <br/>
/// author:xiemiao <br/>
/// date: 2020-03-11  <br/>
/// version 1.0 <br/>
class LoginPresenter extends BasePresenter<LoginView> {
  final LoginModel mModel = LoginModel();

  ///用户表单
  UserInfo mForm = UserInfo();

  @override
  void initState() {
    super.initState();
    //监听微信登录授权
    weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is WeChatAuthResponse) {
        _processWeChatAuthResponse(res);
      }
    });
  }

  ///登录
  void login(String username, String password) async {
    if (Utils.strIsEmpty(username)) {
      mView.showToast("用户名不能为空");
      return;
    }
    if (Utils.strIsEmpty(password)) {
      mView.showToast("密码不能为空");
      return;
    }
    mForm.username = username;
    mForm.password = password;

    mView.showLoading();
    try {
      UserInfo userInfo = await mModel.login(mForm);
      _saveUserInfoAndSetPush(userInfo);
      NavigatorUtils.goBackWithParams(mContext, GlobalCons.RESULT_OK);
    } catch (e) {
      mView.showToast(e.message);
    }
    mView.cancelLoading();
  }

  ///微信登录
  void wxLogin() {
    sendWeChatAuth(scope: "snsapi_userinfo");
  }

  ///保存用户信息和设置推送
  void _saveUserInfoAndSetPush(UserInfo userInfo) {
    //保存本地
    BaseInfo.setToken(userInfo.token);
    BaseInfo.setUserInfo(mContext, userInfo);

    //设置推送别名
    JpushService().setAlias(userInfo.username);
  }

  ///处理微信授权返回结果
  void _processWeChatAuthResponse(WeChatAuthResponse res) {
    if (res.errCode == 0) {
      mView.showToast("授权成功,授权code=${res.code},通过code去获取access_token");
    } else if (res.errCode == -4) {
      mView.showToast("用户拒绝授权");
    } else if (res.errCode == -2) {
      mView.showToast("用户取消授权");
    }
  }
}
